package cn.itcast.cloud.storage;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.AppendObjectRequest;
import com.aliyun.oss.model.AppendObjectResult;
import com.aliyun.oss.model.OSSObject;
import org.junit.Test;

import java.io.*;

public class AppendObjectSample {
    private static String endpoint = "http://oss-cn-zhangjiakou.aliyuncs.com";
    private static String accessKeyId = "LTAIXeZktAHXvAgc";
    private static String accessKeySecret = "iHpKZJ5KiB7imcohA7VgjDzLY2O87w";
    private static String bucketName = "jiaze";
    private static String key = "cloud";
    /**
     * 追加上传
     */
    @Test
    public void appendObject() throws Exception {
        OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        String content = "Thank you for using Aliyun Object Storage Service";
        InputStream instream = new ByteArrayInputStream(content.getBytes());
        Long firstPosition = 0L;

        AppendObjectResult appendObjectResult = client.appendObject(
                new AppendObjectRequest(bucketName, key, instream).withPosition(firstPosition));

        Long nextPosition = appendObjectResult.getNextPosition();
        appendObjectResult = client.appendObject(
                new AppendObjectRequest(bucketName, key, createTempFile())
                        .withPosition(nextPosition));

        OSSObject object = client.getObject(bucketName, key);
        object.getObjectContent().close();

        System.out.println("\t Next position=" + appendObjectResult.getNextPosition() +
                ", CRC64=" + appendObjectResult.getObjectCRC());
        client.deleteObject(bucketName, key);
        System.out.println("\t Object type=" + object.getObjectMetadata().getObjectType() + "\n");
        client.shutdown();
    }

    private File createTempFile() throws IOException {
        File file = File.createTempFile("oss-java-sdk-", ".txt");
        file.deleteOnExit();

        Writer writer = new OutputStreamWriter(new FileOutputStream(file));
        writer.write("abcdefghijklmnopqrstuvwxyz\n");
        writer.write("0123456789011234567890\n");
        writer.close();

        return file;
    }
}
